export default class EventBus {
	cache:Map<any,any>=new Map([])
	constructor (all = []) {
		this.cache = new Map(all);
	}

	once (type, handler) {
		const decor = (...arg) => {
			handler && handler.apply(this, arg);
			this.off(type, decor);
		};
		this.on(type, decor);
		return this;
	}

	on (type, handler) {
		const handlers = this.cache.get(type);
		const added = handlers && handlers.push(handler);
		if (!added) {
			this.cache.set(type, [handler]);
		}
	}

	off (type, handler) {
		const handlers = this.cache.get(type);
		if (handlers) {
			handlers.splice(handlers.indexOf(handler) >>> 0, 1);
		}
	}

	offType (type) {
		this.cache.delete(type);
	}

	emit (type, data) {
		for (const handler of (this.cache.get(type) || []).slice()) handler(data);
	}

	clear () {
		this.cache.clear();
	}
}
